<!DOCTYPE html>
<html xmlns:th="http://www.w3.org/1999/xhtml">
<meta charset="utf-8">
<!--<link rel="stylesheet" href="../../../css/config.css">-->
<style>
    .all {
        height: 40px;
        line-height: 40px;
        border-bottom: 1px solid #ccc;
        border-top: 1px solid #ccc;
        text-indent: 1em;
    }
    .layui-tree-set{
        width: auto !important;
        margin: 10px 0px;
    }
    .layui-tree{
        display: flex;
        flex-wrap: wrap;
    }
    .model {
        border-top: 1px solid #ccc;
        box-sizing: border-box;
    }

    .expirationDate {
        display: none;
    }

    .title-name {
        padding: 10px 20px;
        background: #d7d7d7;
    }

    .submit-search {
        padding: 5px 30px !important;
    }

    #signupForm {
        padding: 0 20px;
    }

    .form-box {
        display: flex;
        padding: 15px 20px;
    }

    .form-box > div {
        width: 20%;
    }

    .control-label {
        width: 8% !important;
        text-align: left !important;
    }

    .checkbox-inline {
        padding-top: 15px !important;
    }

    .sublevel-check {
        flex: 1;
        margin-left: 10px
    }

    .first-check {
        display: flex;
    }

    .checkbox-inline {
        margin-bottom: 10px !important;
    }

    .title-Checkbox {
        width: 120px;
        margin-left: 13px;
        padding-right: 13px;
        border-right: 1px solid #ccc;
        display: flex;
        align-items: center;
    }

    .title-Checkbox > span {
        margin-right: 10px;
        overflow: hidden; /* 确保超出容器的文本被裁剪 */
        white-space: nowrap; /* 确保文本在一行内显示 */
        text-overflow: ellipsis; /* 使用省略号表示文本超出 */
    }

    .all-menu {
        margin: 0 !important;
    }

    .layui-tree {
        display: flex;
        align-items: center;
        padding: 20px 0px 30px 0px;
    }

    .layui-tree-icon {
        height: 14px !important;
        line-height: 12px !important;
        width: 14px !important;
        text-align: center;
        border: 1px solid #c0c4cc;
    }

    .layui-tree-entry:hover {
        padding: 0px !important;
    }
</style>
<head th:include="include :: header"></head>
<body class="gray-bg">
<div class="wrapper wrapper-content animated fadeInRight" style="padding: 0">
    <div class="row">
        <div class="col-sm-12">
            <div class="ibox-content" style="padding: 0">
                <form class="form-horizontal m-t" id="signupForm">
                    <div class="title-name" style="display: none">
                        基本信息
                    </div>
                    <div class="form-box layui-form" style="display: none">
                        <label class="control-label">使用人：</label>
                        <div class="layui-input-inline">
                            <select id="userId" name="userId" lay-search="" lay-filter="select-filter">
                            </select>
                        </div>
                    </div>
                    <div class="form-box" style="display: none">
                        <label class=" control-label">单位名称：</label>
                        <div>
                            <input type="text" class="form-control" id="unitName" name="unitName"
                                   placeholder="请输入单位名称">
                        </div>
                    </div>

                    <div class="form-box" style="display: none">
                        <label class=" control-label">密钥有效期：</label>
                        <div>
                            <select id="period" name="type" class="form-control">
                                <option value="">请选择</option>
                                <option value="0">永久</option>
                                <option value="1">时间限定</option>
                            </select>
                        </div>
                    </div>

                    <div class="form-box expirationDate" style="display: none">
                        <label class="control-label">截止有效期：</label>
                        <div>
                            <input id="entDate" type="hidden"/>
                            <input type="text" class="form-control" id="expirationDate" name="expirationDate"
                                   placeholder="选择截至日期">
                        </div>
                    </div>

                    <div class="form-box" style="display: none">
                        <label class=" control-label">备注：</label>
                        <div>
                            <input type="text" class="form-control" id="remark" name="remark" placeholder="请输入备注">
                        </div>
                    </div>
                    <div class="title-name">
                        资源权限
                    </div>
                    <div class="form-box">
                        <div style="width: 100%;">
                            <!--                            <div class="all"><span>全部</span> <input type="checkbox"></div>-->
                            <div class="form-group children-checkbox" style="border-bottom:1px solid #ccc">
                                <div class="col-sm-12">
                                    <div th:each="courses : ${map}" class="first-check model">
                                        <p class="title-Checkbox">
                                            <span id="title_span" th:text="${courses.key}"
                                                  th:title="${courses.key}"></span>
                                            <input class="all-menu" type="checkbox">
                                        </p>
                                        <div th:id="'ID-tree-demo-' + ${courses.key}" style="width: 90%;"></div>
                                        <!--                                        <div id="ID-tree-demo"></div>-->
                                        <!--                                        <div class="sublevel-check">-->
                                        <!--                                            <label class="checkbox-inline" th:each="resource : ${courses.value}">-->
                                        <!--                                                <input th:text="${resource.eventName}" class="formValue" type="checkbox"-->
                                        <!--                                                       th:data="${courses.key}" th:value="${resource.id}"-->
                                        <!--                                                       th:checked="${resource.isShow}">-->
                                        <!--                                            </label>-->
                                        <!--                                        </div>-->
                                    </div>
                                </div>
                            </div>
                        </div>
                        <input type="hidden" id="ids">

                    </div>
                    <div class="form-group">
                        <div style="text-align: center">
                            <button type="button" class="btn btn-primary submit-search" onclick="save()">提交</button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
<div th:include="include::footer"></div>
<script type="text/javascript" src="/js/webJs/jzweb/keyManagement/add.js?r=220">
</script>
<script>
    let saveSumData = []
    let saveData = []
    let yjSelectData = []
    var dataTreeList = []
    // 勾选模块数据
    let selectDataList = [];
    let sumSelectData = []
    // 总数据
    let sumDataList = [];
    $(function () {
        sessionStorage.removeItem('行业资源_data')
        sessionStorage.removeItem('技能培训_data')
        sessionStorage.removeItem('赛项资源_data')
        sessionStorage.removeItem('证书资源_data')
        sessionStorage.removeItem('金职大讲堂_data')
        handleGetFrom();

    });


    function handleGetFrom() {
        $.ajax({
            url: "/permission/listResource",
            type: "get",
            success: function (r) {
                console.log(r)
                if (r.code == 0) {
                    dataTreeList = r.data
                    layui.use(['tree', 'layer', 'util'], function () {
                        var tree = layui.tree;
                        var layer = layui.layer;
                        var util = layui.util;

                        // 遍历每个课程类别，初始化树形控件

                        $('.first-check.model').each(function () {

                            var courseId = $(this).find('.title-Checkbox span').text();
                            // console.log(courseId)
                            // if(courseId=='1+X证书资源'){
                            //     courseId='证书资源'
                            // }
                            var treeId = 'ID-tree-demo-' + courseId;
                            for (const treeIdKey in dataTreeList) {
                                if (treeIdKey == courseId) {
                                    var data = transformData(dataTreeList[treeIdKey])
                                    // 全选
                                    getAllNodeIds(data).forEach((item) => {
                                        sumDataList.push({
                                            [courseId]: item,
                                        })
                                    })
                                    // console.log(sumDataList, 2222222333)
                                }
                            }
                            // 渲染树形控件
                            tree.render({
                                elem: '#' + treeId,
                                data: data,
                                showCheckbox: true,  // 是否显示复选框
                                onlyIconControl: true,  // 是否仅允许节点左侧图标控制展开收缩
                                id: 'ID-tree-demo-' + courseId,
                                oncheck: function (obj) {
                                    updateAllMenuCheckbox(courseId, obj.elem)
                                    // if (obj.checked) {
                                    //     updateAllMenuCheckbox(courseId, obj.elem)
                                    // } else {
                                    //     detelMenuCheckbox(obj.data, obj.elem, courseId)
                                    //     // console.log(obj.checked, obj.data, 'elem')
                                    // }
                                }
                            });


                            // 绑定 all-menu 复选框的点击事件
                            $(this).find('.all-menu').on('change', function () {
                                var flag = $(this).prop('checked'); // 获取当前全选复选框的状态
                                var treeInstanceId = 'ID-tree-demo-' + courseId;
                                console.log(data, 2020, flag)
                                if (flag) {
                                    // 全选复选框被选中时，选中所有树形控件中的节点
                                    tree.setChecked(treeInstanceId, getAllNodeIds(data));
                                } else {
                                    // 全选复选框未被选中时，取消选中所有树形控件中的节点
                                    // tree.setChecked(treeInstanceId, JSON.parse([]));
                                    let resultData = []
                                    let userId = JSON.parse(sessionStorage.getItem('qx_USERID'))
                                    tree.reload(treeInstanceId, {});
                                    sessionStorage.removeItem(courseId + '_data')
                                    // tree.setChecked(treeInstanceId, [])
                                    data.forEach((item) => {
                                        resultData.push({
                                            userId: userId,
                                            allocationId: item.id
                                        })
                                    })
                                    // $.ajax({
                                    //     type: 'delete',
                                    //     url: "/permission/batchDelete",
                                    //     data: JSON.stringify(resultData),
                                    //     contentType: "application/json", // 指定发送的内容类型为 JSON
                                    //     success: function (r) {
                                    //         if (r.code == 0) {
                                    //             layer.msg('操作成功！')
                                    //         } else {
                                    //             layer.msg('操作失败！')
                                    //         }
                                    //     }
                                    // });

                                }
                            });

                        });


                        getIDlisg()

                        function getIDlisg() {
                            let userID = JSON.parse(sessionStorage.getItem('qx_USERID'))
                            $.ajax({
                                url: "/permission/list",
                                type: "get",
                                data: {
                                    userId: userID
                                },
                                success: function (r) {
                                    for (const rKey in r.data) {
                                        r.data[rKey].forEach((item) => {
                                            if (item.groupType.split(',').length > 0) {
                                                item.groupType.split(',').forEach((eitem) => {
                                                    yjSelectData.push(item.allocationId + '-' + item.type + '-' + eitem)
                                                })
                                            } else {
                                                yjSelectData.push(item.allocationId + '-' + item.type + '-' + item.groupType)
                                            }
                                        })
                                        console.log(yjSelectData, rKey, 'arr')
                                        tree.setChecked('ID-tree-demo-' + rKey, yjSelectData)
                                    }

                                }
                            })
                        }

                        // 按钮事件
                        util.event('lay-on', {
                            getChecked: function (othis) {
                                var courseId = othis.data('course-id');
                                var treeId = 'ID-tree-demo-' + courseId;
                                var checkedData = tree.getChecked(treeId); // 获取选中节点的数据
                                layer.alert(JSON.stringify(checkedData), {shade: 0});
                                // console.log(checkedData);
                            },
                            setChecked: function (othis) {
                                var courseId = othis.data('course-id');
                                var treeId = 'ID-tree-demo-' + courseId;
                                tree.setChecked(treeId, [12, 16]); // 勾选对应 id 值的节点
                            },
                            reload: function (othis) {
                                var courseId = othis.data('course-id');
                                var treeId = 'ID-tree-demo-' + courseId;
                                tree.reload(treeId, {}); // 重载实例
                            }
                        });

                        // function detelMenuCheckbox(data, domsb, courseId) {
                        //     let userId = JSON.parse(sessionStorage.getItem('qx_USERID'))
                        //     let arrList = []
                        //     sumDataList.forEach((item) => {
                        //         if (Object.keys(item)[0] == courseId) {
                        //             arrList.push(item[Object.keys(item)[0]])
                        //         }
                        //     })
                        //     let dom = $($($(domsb.closest('.first-check.model')).children()[0]).children()[1])
                        //     selectDataList = []
                        //     // 勾选的数据
                        //     var checkedData = tree.getChecked('ID-tree-demo-' + courseId); // 获取选中节点的数据
                        //     // console.log(checkedData);
                        //     getAllNodeIds(checkedData).forEach((item) => {
                        //         selectDataList.push(item)
                        //
                        //     })
                        //     if (selectDataList.length == arrList.length) {
                        //         dom.prop('checked', true);
                        //     } else {
                        //         dom.prop('checked', false);
                        //     }
                        //
                        //     arrmerList.forEach((item, index) => {
                        //         if (item.startsWith(data.id)) {
                        //             console.log(item, data.id, 'start')
                        //             arrmerList.splice(index, 1)
                        //         }
                        //     })
                        //
                        // }

                        // 辅助函数：更新 all-menu 复选框的状态
                        function updateAllMenuCheckbox(courseId, elem) {
                            let arrList = []
                            // console.log(sumDataList)
                            sumDataList.forEach((item) => {
                                if (Object.keys(item)[0] == courseId) {
                                    arrList.push(item[Object.keys(item)[0]])
                                }
                            })
                            let dom = $($($(elem.closest('.first-check.model')).children()[0]).children()[1])
                            selectDataList = []
                            // 勾选的数据
                            var checkedData = tree.getChecked('ID-tree-demo-' + courseId); // 获取选中节点的数据
                            // console.log(checkedData);
                            getAllNodeIds(checkedData).forEach((item) => {
                                selectDataList.push(item)
                            })
                            // console.log(selectDataList, '选择')
                            // console.log(selectDataList, arrList.length, dom, '选择')
                            if (selectDataList.length == arrList.length) {
                                dom.prop('checked', true);
                            } else {
                                // console.log(dom)
                                dom.prop('checked', false);
                            }
                            var splitList = []
                            // console.log(selectDataList, sumDataList)
                            selectDataList.forEach((item) => {
                                if (item.split('-').length == 3) {
                                    splitList.push(item)
                                }
                            })
                            sessionStorage.setItem(courseId + '_data', JSON.stringify(selectDataList))
                            console.log(selectDataList, '选择')
                            // 用于存储前缀和后缀的映射
                            const prefixMap = {};

// 遍历数组，提取前缀和后缀
                            splitList.forEach(str => {
                                const parts = str.split('-');
                                const prefix = `${parts[0]}-${parts[1]}`;
                                const suffix = parts[2];

                                if (!prefixMap[prefix]) {
                                    prefixMap[prefix] = [];
                                }
                                prefixMap[prefix].push(suffix);
                            });

// 构建结果数组
                            const resultArray = Object.keys(prefixMap).map(prefix => {
                                const suffixes = prefixMap[prefix];
                                return `${prefix}-${suffixes.join(',')}`;
                            });
                            // console.log(resultArray, '提交数据')
                            // let resultData = []
                            resultArray.forEach((item) => {
                                saveData.push(item)
                            })

                        }

                        function transformData(data) {
                            // console.log(data,2222222)
                            if (!Array.isArray(data)) {
                                return data; // 如果不是数组，直接返回
                            }

                            return data.map(item => {
                                // 创建一个新的对象，复制原有对象的所有属性
                                const newItem = {...item};

                                // 修改 title 为 name
                                if (newItem.name) {
                                    newItem.title = newItem.name;
                                } else {
                                    handlePd(newItem)
                                }

                                // 修改 children 为 permissionList
                                if (newItem.permissionList) {
                                    newItem.children = transformData(newItem.permissionList); // 递归处理子节点

                                }
                                return newItem;
                            });
                        }

                        // 辅助函数：获取所有节点的 id
                        function getAllNodeIds(data) {
                            var ids = [];

                            function traverse(nodes) {
                                for (var i = 0; i < nodes.length; i++) {
                                    ids.push(nodes[i].id);
                                    if (nodes[i].children && nodes[i].children.length > 0) {
                                        traverse(nodes[i].children);
                                    }
                                }
                            }

                            traverse(data);
                            return ids;
                        }

                        // 数据插入
                        function handlePd(newItem) {
                            console.log(newItem, 'newItem')
                            // 赛项资源
                            if (newItem.type == 0 && newItem.eveMoName == '赛项资源') {
                                newItem.title = '赛项规程'
                            }
                            if (newItem.type == 1 && newItem.eveMoName == '赛项资源') {
                                newItem.title = '在线题库'
                            }
                            if (newItem.type == 2 && newItem.eveMoName == '赛项资源') {
                                newItem.title = '竞赛试题'
                            }
                            if (newItem.type == 3 && newItem.eveMoName == '赛项资源') {
                                newItem.title = '模拟赛场'
                            }
                            if (newItem.type == 4 && newItem.eveMoName == '赛项资源') {
                                newItem.title = '专家点评'
                            }
                            if (newItem.type == 5 && newItem.eveMoName == '赛项资源') {
                                newItem.title = '技能示范'
                            }
                            if (newItem.type == 6 && newItem.eveMoName == '赛项资源') {
                                newItem.title = '赛场再现'
                            }
                            if (newItem.type == 7 && newItem.eveMoName == '赛项资源') {
                                newItem.title = '物料清单'
                            }

                            //  1+x证书
                            if (newItem.type == 0 && newItem.eveMoName == '证书资源') {
                                newItem.title = '证书标准'
                            }
                            if (newItem.type == 1 && newItem.eveMoName == '证书资源') {
                                newItem.title = '在线题库'
                            }
                            if (newItem.type == 2 && newItem.eveMoName == '证书资源') {
                                newItem.title = '课程标准'
                            }
                            if (newItem.type == 3 && newItem.eveMoName == '证书资源') {
                                newItem.title = '模拟考场'
                            }
                            if (newItem.type == 4 && newItem.eveMoName == '证书资源') {
                                newItem.title = '考评标准'
                            }
                            if (newItem.type == 5 && newItem.eveMoName == '证书资源') {
                                newItem.title = '技能参考'
                            }
                            if (newItem.type == 6 && newItem.eveMoName == '证书资源') {
                                newItem.title = '考评物料'
                            }

                            //  技能培训
                            if (newItem.type == 5 && newItem.eveMoName == '技能培训') {
                                newItem.title = '技能参考'
                            }
                            if (newItem.type == 1 && newItem.eveMoName == '技能培训') {
                                newItem.title = '在线题库'
                            }

                            //  行业资源
                            if (newItem.type == 5 && newItem.eveMoName == '行业资源') {
                                newItem.title = '资源详情'
                            }

                            //  金职大讲堂
                            if (newItem.type == 5 && newItem.eveMoName == '金职大讲堂') {
                                newItem.title = '资源详情'
                            }

                            //  分组
                            if (newItem.groupType) {
                                switch (newItem.groupType) {
                                    case '1':
                                        newItem.title = '中职组'
                                        break
                                    case '2':
                                        newItem.title = '高校组'
                                        break
                                    case '3':
                                        newItem.title = '教师组'
                                        break
                                    case '4':
                                        newItem.title = '国际组'
                                        break
                                    default:
                                        newItem.title = '通用'
                                }
                            }


                        }


                    });


                }
            }
        });
    }

    function save() {
        let sumData = []
        let splitList = []
        let resultData = []
        let hyList = JSON.parse(sessionStorage.getItem('行业资源_data')) ? JSON.parse(sessionStorage.getItem('行业资源_data')) : []
        let jnList = JSON.parse(sessionStorage.getItem('技能培训_data')) ? JSON.parse(sessionStorage.getItem('技能培训_data')) : []
        let sxList = JSON.parse(sessionStorage.getItem('赛项资源_data')) ? JSON.parse(sessionStorage.getItem('赛项资源_data')) : []
        let zsList = JSON.parse(sessionStorage.getItem('证书资源_data')) ? JSON.parse(sessionStorage.getItem('证书资源_data')) : []
        let jzdjtList = JSON.parse(sessionStorage.getItem('金职大讲堂_data')) ? JSON.parse(sessionStorage.getItem('金职大讲堂_data')) : []

        if (hyList.length > 0) {
            hyList.forEach((item) => {
                sumData.push(item)
            })
        }
        if (jnList.length > 0) {
            jnList.forEach((item) => {
                sumData.push(item)
            })
        }
        if (sxList.length > 0) {
            sxList.forEach((item) => {
                sumData.push(item)
            })
        }
        if (zsList.length > 0) {
            zsList.forEach((item) => {
                sumData.push(item)
            })
        }
        if (jzdjtList.length > 0) {
            jzdjtList.forEach((item) => {
                sumData.push(item)
            })
        }


        // console.log(selectDataList, sumDataList)
        sumData.forEach((item, index) => {
            if (item.split('-').length == 3) {
                splitList.push(item)
                splitList.splice(index, 1)
            }
        })
        // 用于存储前缀和后缀的映射
        const prefixMap = {};
// 遍历数组，提取前缀和后缀
        splitList.forEach(str => {
            const parts = str.split('-');
            const prefix = `${parts[0]}-${parts[1]}`;
            const suffix = parts[2];

            if (!prefixMap[prefix]) {
                prefixMap[prefix] = [];
            }
            prefixMap[prefix].push(suffix);
        });
// 构建结果数组
        const resultArray = Object.keys(prefixMap).map(prefix => {
            const suffixes = prefixMap[prefix];
            return `${prefix}-${suffixes.join(',')}`;
        });

        let dataList = noRepeat(resultArray)
        console.log(dataList, 'dataList')
        dataList.forEach((item) => {
            resultData.push({
                userId: JSON.parse(sessionStorage.getItem('qx_USERID')),
                allocationId: item.split('-')[0],
                type: item.split('-')[1],
                groupType: item.split('-')[2],
            })
        })
        $.ajax({
            type: 'post',
            url: "/permission/save",
            data: JSON.stringify(
                {
                    userId: JSON.parse(sessionStorage.getItem('qx_USERID')),
                    jzPermissionList: resultData
                }
            ),
            contentType: "application/json", // 指定发送的内容类型为 JSON
            success: function (r) {
                if (r.code == 0) {
                    parent.layer.msg(r.msg);
                    parent.reLoad();
                    var index = parent.layer.getFrameIndex(window.name); // 获取窗口索引
                    parent.layer.close(index);
                    sessionStorage.removeItem('行业资源_data')
                    sessionStorage.removeItem('技能培训_data')
                    sessionStorage.removeItem('赛项资源_data')
                    sessionStorage.removeItem('证书资源_data')
                    sessionStorage.removeItem('金职大讲堂_data')
                }
            },
        })
    }

    function noRepeat(arr) {
        var newArr = [...new Set(arr)]; //利用了Set结构不能接收重复数据的特点
        return newArr
    }
</script>
</body>
</html>
